<template>
  <!-- 选择对话框 -->
  <t-dialog v-model:visible="visible" attach="body" header="选择收款模板" width="60%">
    <!-- 容器 -->
    <div class="container">
      <t-space class="left" direction="vertical">
        <!-- 公司 -->
        <t-select
          v-model:value="searchParams.companyId"
          :options="companySimpleList"
          :keys="{ label: 'name', value: 'id' }"
          label="归属公司："
          filterable
          @change="handleChangeCompany"
        />
        
        <!-- 模板树 -->
        <t-tree
          :data="categoryTree"
          activable
          expand-on-click-node
          hover
          :keys="{ label: 'name', value: 'id' }"
          max-height="calc(100vh - 380px)"
          @click="handleClickCategoryTree"
        />
      </t-space>
      <t-divider class="divider" layout="vertical" />
      <div v-show="searchParams.modelId" class="right">
        <t-table
          ref="templateTableRef"
          row-key="id"
          :data="templatePayList"
          :columns="columns"
          bordered
          size="small"
          stripe
          hover
        >
          <template #engineeringStage="{ row }">
            <t-cascader
              v-model:value="row.engineeringStage"
              :options="stageTree"
              :keys="{ value: 'id', label: 'stageName' }"
              placeholder=""
              :readonly="true"
              :borderless="true"
              class="text-only-cascader"
            />
          </template>
        </t-table>
      </div>
      <t-empty v-show="!searchParams.modelId" class="right" title="请先选择模板" style="margin-top: 30vh" />
    </div>
    <template #footer>
      <t-button theme="default" @click="visible = false">取消</t-button>
      <t-button theme="primary" @click="handleConfirm" :disabled="!searchParams.modelId">确认</t-button>
    </template>
  </t-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { getCompanyList } from '@/api/system/dept';
import { collectionConfigCRUD, engineeringConfigCRUD, collectionModelConfigCRUD } from '@/api/config/common-config';
import listToTree from '@/utils/listToTree';

const visible = ref(false);
const searchParams = reactive({
  companyId: null,
  modelId: null
});

// 当前模板的payList数据
const templatePayList = ref([]);

// 公司精简列表
const companySimpleList = ref([]);
const handleGetCompanySimpleList = async () => {
  return getCompanyList().then((data) => {
    companySimpleList.value = data;
    searchParams.companyId = data[0].id;
    handleGetCategory();
  });
};

// 公司change
const handleChangeCompany = () => {
  searchParams.modelId = null;
  templatePayList.value = [];
  handleGetCategory();
}

// 模板列表和树
const categoryList = ref([]);
const categoryTree = ref([]);
const handleGetCategory = () => {
  const params = {
    companyId: searchParams.companyId,
    pageSize: -1,
  };
  collectionModelConfigCRUD.page(params).then((data) => {
    console.log(categoryList.value,'categoryList.value')
    console.log(categoryTree.value,'categoryTree.value')
    categoryList.value = data.list;
    categoryTree.value = listToTree(data.list);
  });
};

// 精简节点树
const stageTree = ref([]);
const handleGetSimpleStageTree = () => {
  const params = {
    pageSize:-1
  }
  engineeringConfigCRUD.page(params).then((data) => {
    stageTree.value = listToTree(data.list);
  });
};

// 处理点击模板树
const handleClickCategoryTree = async ({ node }) => {
  if (!node.data.children) {
    searchParams.modelId = node.value;
    // 获取该模板对应的payList数据
    const res = await collectionConfigCRUD.page({
      modelId: searchParams.modelId,
      pageSize: -1
    });
    templatePayList.value = res.list.map(item => ({
      ...item,
      reminderForCollectionStage: item.engineeringStage
    }));
  }
};
const open = () => {
  visible.value = true;
  // 初始化
  handleGetCompanySimpleList();
  handleGetSimpleStageTree();

};
// 处理确认选择
const handleConfirm = () => {
  if (templatePayList.value.length === 0) {
    MessagePlugin.warning('该模板没有配置收款分期');
    return;
  }
  
  emits('confirm', templatePayList.value,searchParams.modelId);
  visible.value = false;
};

// 组件 emits
const emits = defineEmits(['confirm']);

// columns
const columns = [
  { colKey: 'payNumber', title: '期数', width: 60 },
  { colKey: 'paymentStage', title: '收款阶段', width: 100 },
  { colKey: 'engineeringStage', title: '收款节点', width: 250 },
  { colKey: 'proportion', title: '收款比例(%)', width: 180 },
].map(column => ({ ...column, align: 'center' }));


// 暴露给父组件
defineExpose({
  open
});
</script>

<style lang="less" scoped>
// 容器
.container {
  display: flex;
  justify-content: center;
  align-items: flex-start;

  .left {
    width: 280px;
    height: 100%;
    overflow: hidden;

    :deep(.t-tree) {
      padding-right: 8px;

      &::-webkit-scrollbar {
        width: 8px;
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 6px;
        border: 2px solid transparent;
        background-clip: content-box;
        background-color: var(--td-scrollbar-color);
      }
    }
  }

  .divider {
    height: 100%;
  }

  .right {
    // width: calc(100% - 325px);
    flex:1;
  }
}
</style>